import prompt from '@ohos.prompt';
import dataRdb from '@ohos.data.rdb';
import { User } from 'ets/db/user/User';
import { Rdb } from 'ets/db/Rdb'
//import List from '@ohos.util.List';


class UserAPI {
  private tableName: string = ''
  private columns: Array<string> = []
  private rdb: Rdb = null
  private sql_create_table = ''


  constructor() {//建表
    this.tableName = 'user'
    this.columns = ['id', 'name', 'sex', 'password', 'tel']
    this.sql_create_table = 'CREATE TABLE IF NOT EXISTS '
    + this.tableName + '('
    + 'id INTEGER PRIMARY KEY AUTOINCREMENT, '
    + 'name TEXT NOT NULL, '
    + 'sex TEXT, '
    + 'password TEXT, '
    + 'tel TEXT)';
    this.rdb = new Rdb(this.sql_create_table)
    this.rdb.getRdbStore()
  }

  //userInf:any=[]
  // 插入数据
  insertUser(user) {
    const valueBucket = JSON.parse(JSON.stringify(user));
    this.rdb.rdbStore.insert(this.tableName, valueBucket, function (err, ret) {
      console.log('insert done: ' + ret);
      prompt.showToast({ message: '添加用户成功！' });
    });
  }

  // 根据用户名查询用户信息
  async queryUserByName(name) {
    let resultList;
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    predicates.equalTo('name', name);
    let ret = await this.queryFromDB(predicates);
    resultList = this.getListFromResultSet(ret);
    // console.info(resultList)
    return resultList;
  }
  // 根据mima名查询用户信息
  async queryUserBypassword(password) {
    let resultList;
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    predicates.equalTo('password', password);
    let ret = await this.queryFromDB(predicates);
    resultList = this.getListFromResultSet(ret);
    return resultList;
  }

  // 查询全部用户信息
  async queryUserAll() {
    let resultList;
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    let ret = await this.queryFromDB(predicates);
    resultList = this.getListFromResultSet(ret);
    return resultList;
  }

  // 根据条件查询数据库
  async queryFromDB(predicates) {
    let resultList;
    let promiseQuery = this.rdb.rdbStore.query(predicates, this.columns);
    await promiseQuery.then((resultSet) => {
      resultList = resultSet;
    }).catch((err) => {
      console.log("query err" + JSON.stringify(err));
    });
    return resultList;
  }

  // 将查询到的结果封装用户列表
  getListFromResultSet(resultSet) {
    let userList = [];
    for (let i = 0; i < resultSet.rowCount; i++) {
      resultSet.goToNextRow();
      let user = new User(
        resultSet.getDouble(resultSet.getColumnIndex('id')),
        resultSet.getString(resultSet.getColumnIndex('name')),
        resultSet.getString(resultSet.getColumnIndex('sex')),
        resultSet.getString(resultSet.getColumnIndex('password')),
        resultSet.getString(resultSet.getColumnIndex('tel'))
      );
     //console.info("1:"+user.getPassword())//debug

      userList.push(user)
      //console.info(userList[0])
    }
    return userList;
  }

  getInfList(resultSet) {
    let List : any = [];
     if(resultSet.rowCount!=-1) {
       for (let i = 0; i < resultSet.rowCount; i++) {

         //console.info("i:", i) //debug
         resultSet.goToNextRow();
         let user = new User(
           resultSet.getDouble(resultSet.getColumnIndex('id')),
           resultSet.getString(resultSet.getColumnIndex('name')),
           resultSet.getString(resultSet.getColumnIndex('sex')),
           resultSet.getString(resultSet.getColumnIndex('password')),
           resultSet.getString(resultSet.getColumnIndex('tel'))
         );
         //console.info("get:" + user.getPassword()) //debug
         List[0] = user.getId()
         List[1] = user.getName()
         List[2] = user.getSex()
         List[3] = user.getPassword()
         List[4] = user.getTel()
       }
     }

        return List
  }


  getlist(){
    return
  }

  async getBackByName(name) {
    let inf:any=[];
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    predicates.equalTo('name', name);
    let ret = await this.queryFromDB(predicates);
    inf = this.getInfList(ret);
    //console.log(password)
    return inf;
  }

  // 删除全部数据
  async deleteAll() {
    let result
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    await this.rdb.rdbStore.delete(predicates).then((rows) => {
      result = rows;
      prompt.showToast({ message: '删除数据，rows:' + rows });
    });
    return result
  }

  // 更新数据，暂时未使用
  updateUser(user) {
    const valueBucket = JSON.parse(JSON.stringify(user));
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    predicates.equalTo('id', user.id);
    this.rdb.rdbStore.update(valueBucket, predicates, function (err, ret) {
      prompt.showToast({ message: '更新数据，ret:' + ret });
    });
  }

  // 删除数据，暂时未使用
  deleteUserById(userId) {
    let predicates = new dataRdb.RdbPredicates(this.tableName);
    predicates.equalTo('id', userId);
    this.rdb.rdbStore.delete(predicates, function (err, rows) {
      prompt.showToast({ message: '删除数据，rows::' + rows });
    });
  }
}

export default new UserAPI()


//根据姓名删除
//更新
